package com.jq.jq.web;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.*;

@RestController
public class ApiController {

    @Value("${file.path}")
    private String filePath;

    @PostConstruct
    void init() {
        //如果文件不存在则创建
        if (!FileUtil.exist(filePath)) {
            FileUtil.writeUtf8String("[]", filePath);
        }
    }


    @PostMapping("/getInfo")
    public JSONArray getInfo() {
        String json = FileReader.create(new File(filePath)).readString();
        return JSONUtil.parseArray(json);
    }

    @PostMapping("/getCount")
    public Integer getCount() {
        return getInfo().size();
    }

    @PostMapping("/submit")
    public String submit(@RequestParam("username") String username) {
        if (username == null || username.isEmpty()) {
            return "请输入名称,不能为空！";
        }
        String json = FileReader.create(new File(filePath)).readString();
        JSONArray objects = JSONUtil.parseArray(json);

        //如果不存在则写入最后一行
        if (!objects.contains(username)) {
            objects.add(username);
            FileUtil.writeUtf8String(JSONUtil.toJsonPrettyStr(objects), filePath);
        }
        return getRandomString(objects, username);

    }

    private String getRandomString(JSONArray objects, String username) {
        // 随机获取一位
        if (!objects.isEmpty()) {
            Random random = new Random();
            int index = random.nextInt(objects.size());
            String name = objects.getStr(index);
            // 不能匹配到自己
            if (name.equals(username) && objects.size() > 1) {
                return getRandomString(objects, username);
            }
            return "恭喜 匹配到 【" + name + "】小伙伴！";
        }
        return "未发现小伙伴";
    }

}
